package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import com.itheima.reggie.pojo.User;
import com.itheima.reggie.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 移动端用户管理
 */
@Slf4j
@RestController
@RequestMapping("user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 发送短信
     */
    @PostMapping("sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session) {
        //手机号
        String phone = user.getPhone();
        //验证码（存入session中）
        String code = RandomStringUtils.random(4, false, true);
        //调用SMSUtils工具类，发送短信
        //SMSUtils.send(phone, code);
        //模拟发送短信
        log.info("短信已发送：{}", code);
        //将code存入redis中
        //session.setAttribute(phone, code);
        redisTemplate.opsForValue().set(phone, code, 120, TimeUnit.SECONDS);
        return R.success("短信发送成功");
    }

    /**
     * 验证码登录
     */
    @PostMapping("login")
    public R<User> login(@RequestBody Map<String, String> map, HttpSession session) {

        //1. 获取请求参数
        String phone = map.get("phone");
        String code = map.get("code");

        //2. 判断验证码是否一致
        //String code2 = (String) session.getAttribute(phone);
        String code2 = (String)redisTemplate.opsForValue().get(phone);
        if (!StringUtils.equals(code, code2)) {
            return R.error("验证码错误");
        }

        //3. 判断手机号是否是新用户 select * from user where phone=?
        User user = userService.lambdaQuery()
                .eq(User::getPhone, phone)
                .one();
        if (user == null) {
            //说明新用户，添加操作
            user = new User(); //防止空指针
            //设置手机号，状态
            user.setPhone(phone);
            user.setStatus(1);
            userService.save(user); //保存之后，id有值
        }

        //4. 登录成功，和后台员工登录操作一样
        session.setAttribute("user", user.getId());
        //删除redis中的验证码
        redisTemplate.delete(phone);
        return R.success(user);
    }

}
